package com.lkd.handler;
import com.google.common.collect.Lists;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.StatusInfo;
import com.lkd.contract.VmStatusContract;
import com.lkd.emq.Topic;
import com.lkd.exception.LogicException;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;

@Component
@Topic(TopicConfig.VMS_STATUS_TOPIC)
@Slf4j
public class VmsRepairHandler implements MsgHandler {
    @Autowired
    VMService vmService;
    @Autowired
    TaskService taskService;
    @Override
    public void process(String jsonMsg) throws IOException {
        //获取机器发送的豹纹 解析协议类
        VmStatusContract contract = JsonUtil.getByJson(jsonMsg, VmStatusContract.class);
        if (contract == null)return;
        List<StatusInfo> statusInfo = contract.getStatusInfo();
        String innerCode = contract.getInnerCode();
        if (innerCode == null || CollectionUtils.isEmpty(statusInfo)){
            log.warn("机器码或者机器状态不存在");
            return;
        }
        log.warn("机器" + innerCode + "发送状态数据成功");
        //判断协议类中机器的状态 是否存在异常
        if (statusInfo.stream().anyMatch(status->status.isStatus()==false)){
            VmVO vmInfo = vmService.getVMInfo(innerCode);
            if (vmInfo == null){
                log.info("机器不存在" + innerCode);
                throw new LogicException("机器不存在");
            }
            //查询当日工单redis列表中最少工单数的人员  键需要参数  区域id
           int id = taskService.getLeastTsakUser(vmInfo.getRegionId(),true);
            //对参数进行封装
            if (id != 0){
                TaskViewModel taskViewModel = new TaskViewModel();
                taskViewModel.setCreateType(0);//自动创建工单
                taskViewModel.setInnerCode(vmInfo.getInnerCode());//机器内编码
                taskViewModel.setUserId(id);//指派人id
                taskViewModel.setAssignorId(0);
                taskViewModel.setProductType(VMSystem.TASK_TYPE_REPAIR);
                taskViewModel.setDesc(jsonMsg);
                log.info("机器创建工单");
                taskService.createTask(taskViewModel);
            }

        }

    }
}
